package com.example.demo;

import com.alibaba.druid.pool.DruidDataSource;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import javax.sql.DataSource;
import java.net.URISyntaxException;
import java.util.Map;

@Configuration
@Slf4j
public class MarsHiKariConfig {
    //
    @Value("${spring.datasource.url}")
    private String url;

    private DruidDataSource current;

    private Map<Integer, DruidDataSource> dataSourceMap;

    private CustomHiKariDatasource customHiKariDatasource = new CustomHiKariDatasource();

//
//    private String driverClassName;
//
//    private String username;
//
//    @Bean(name = "dataSource")
//    public DataSource dataSource() throws URISyntaxException {
//        RestTemplate restTemplate = new RestTemplate();
//        HttpHeaders httpHeaders = new HttpHeaders();
//        httpHeaders.set("X-Vault-Token", "s.vvLZKiJdC05MTr7xzFV5TX5U");
//        HttpEntity entity = new HttpEntity(httpHeaders);
//        ResponseEntity<Map> result = restTemplate.exchange(new URI("http://localhost:8200/v1/database/static-creds/smb-dev"), HttpMethod.GET, entity, Map.class);
//
//
//        return DataSourceBuilder.create().driverClassName("com.mysql.cj.jdbc.Driver").url(url).username("smbuser").password("5ABcytPzOd-mDz7h9-3n").<HikariDataSource>build();
//    }

    @Bean(name = "dataSource")
    public DataSource dataSource() throws URISyntaxException {
        log.info("use root datasource");
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername("root");
        dataSource.setPassword("root123");
        customHiKariDatasource.updateDataSourceMap("1", dataSource);
        return customHiKariDatasource;
    }

    @Scheduled(cron = "* 26 10 * * ?")
    public void update() {
        log.info("use mars datasource");
        DruidDataSource hikariDataSource2 = new DruidDataSource();
        hikariDataSource2.setUrl(url);
        hikariDataSource2.setUsername("root");
        hikariDataSource2.setPassword("root123");
        customHiKariDatasource.updateDataSourceMap("1", hikariDataSource2);
    }

}
